package com.geyue.controller;

import com.geyue.core.model.Admin;
import com.geyue.core.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;

/**
 * Created by Lyon on 2017/5/25.
 */
@Controller
public class IndexController {

    @Autowired
    private AdminService adminService;

    /**
     * 跳转登录
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        return "login";
    }

    /**
     * 跳转登录
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    /**
     * 登录
     * @param userName
     * @param password
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(String userName, String password, HttpSession session) {


        Admin admin = new Admin();
        admin.setUsername(userName);
        admin.setPassword(password);

        Admin login = adminService.getOne(admin);

        if(login != null){
            session.setAttribute("admin",login);
            return "redirect:main";
        }

        return "/login";
    }

    @RequestMapping(value = "/main.html",method = RequestMethod.GET)
    public String main1(HttpSession session){
        Admin admin = (Admin) session.getAttribute("admin");

        if(admin == null)
            return "error";

        return "main";
    }

    @RequestMapping(value = "/out", method = RequestMethod.GET)
    public String out(HttpSession session) {
        session.invalidate();
        return "redirect:login";
    }

    /**
     * 跳转登录
     * @return
     */
    @RequestMapping(value = "/main", method = RequestMethod.GET)
    public String main(HttpSession session, Model model) {
        Admin admin = (Admin) session.getAttribute("admin");

        if(admin == null)
            return "redirect:login";

        model.addAttribute("teacher",adminService.getOneByKey(admin.getId()));
        return "index";
    }
}
